/**
 * @author joshua
 */


joshua.embarques.winAgregar=Ext.extend(Ext.Window,{
	layout      : 'fit',
	width: 1000,
	height: 520,
	closeAction :'close',
	resizable:false,
	maximizable:false,
	buttonAlign:'center',
    modal: true,
	iconCls:'avioniconoadd',
	title:'Agregar embarque',
	peso_total:0,

	initComponent: function(){
		
        var ffiledss= [
            {name:'costo_total', type: 'string'},
            {name:'prefijo', type: 'string'},
            {name:'id', type: 'string',mapping : 'id'},
            {name:'estatus', type: 'string'},
            {name:'id_envio', type: 'string'},
            {name:'fecha', type: 'string'},
            {name:'remitente', type: 'string'},
            {name:'destinatario', type: 'string'},
            {name:'completo', type: 'string'},
            {name:'peso', type: 'string'}
        ];

    // create the data store
    this.firstGridStore = new Ext.data.JsonStore({
		url: 'Servicios/s.php',
		method: 'POST',
		root: 'data',
		//autoLoad:true,
		baseParams:{
			cmd:'gridEmbarque',
			className:'Envio'
		},
		totalProperty: 'numFilas',
		fields: ffiledss
    });


	// Column Model shortcut array
	var cols = [
		new Ext.grid.RowNumberer(),
		{header: joshua.util.icono.boleto+' Guia',width:140,  iconCls:'usuario_borrar', dataIndex: 'id_envio', sortable: true,renderer:joshua.envios.coloreafila},
		{header: joshua.util.icono.remitente+' Remitente',width:140, dataIndex: 'remitente', sortable: true},
		{header: joshua.util.icono.destinatario	+' Destinatario',width:140,  dataIndex: 'destinatario', sortable: true}
	];


		

	// declare the source Grid
    this.firstGrid = new Ext.grid.GridPanel({
		ddGroup          : 'secondGridDDGroup',
		store            : this.firstGridStore,
		columns          : cols,
		enableDragDrop   : true,
		frame:true,
        border: false,
		iconCls:'package_go',
		stripeRows       : true,
	//	autoExpandColumn : 'name',
		width            : 475,
		region           : 'west',
		title            : 'Envios listos para embarque'
    });

    this.secondGridStore = new Ext.data.JsonStore({
        fields : ffiledss,
		root   : 'data'
    });

	this.labelpeso=new Ext.form.Label({
			style:'padding-top:2px;font-size:14pt;color:#15428B;font-weight:bold;',
			text:'0Kg/0Lb'
		});
		
    // create the destination Grid
    this.secondGrid = new Ext.grid.GridPanel({
		ddGroup          : 'firstGridDDGroup',
		store            : this.secondGridStore,
		columns          : cols,
		frame:true,
        border: false,
		iconCls:'avioniconoadd',
		enableDragDrop   : true,
		stripeRows       : true,
		width            : 475,
		region           : 'east',
		bbar:['->',this.labelpeso],
		title            : 'Paquetes para embarque'
    });

	var botones_centro= new Ext.Panel({
		region:'center',
		width:25,
		frame:true,
		html:'<div id="btnDerE" style="margin-top:180px;height:20px"></div><div id="btnIzqE" style="margin-top:5px;height:20px"></div>'
	});
	
		Ext.apply(this,{
            layout   : 'border',
            manager: Ext.managerEnlace,
            items    : [this.firstGrid,botones_centro,this.secondGrid],
            buttons:[{
            text:'<b>Guardar</b>',
            iconCls:'save',
            scope:this,
            handler: function(){
                    if(this.secondGrid.store.getCount()>0){
                        var wiii= new joshua.embarques.winFinalizar({
                            secondGridStore: this.secondGridStore
                        });

                        wiii.show(this);//joshua.clientes.interfaz.show(this);
                    }
                    else
                        joshua.funciones.alert('aviso','Embarque vacio',"Por favor seleccione envios para el embarque");
                }
            },{
                text:'<b>Cancelar</b>',
                iconCls:'delete',
                scope:this,
                handler:function(){
                    this.hide();
                }
            }]
		});
		joshua.embarques.winAgregar.superclass.initComponent.apply(this,arguments);

        this.on({
            show: function (){
                this.firstGridStore.reload();
            }
        });
	},
	
        

 	onRender:function(){
 		joshua.embarques.winAgregar.superclass.onRender.apply(this,arguments);


		var f=this;
	
		setTimeout(function (){
		
		//para mandar del segundo al primer grid
		var firstGridDropTarget = new Ext.dd.DropTarget(f.firstGrid.getView().el.dom.childNodes[0].childNodes[1], {
		ddGroup    : 'firstGridDDGroup',
		copy       : true,
		//scope:this,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = f.firstGridStore.findExact('id', record.data.id);
				// if not found
				if (foundItem  == -1) {
					f.firstGridStore.add(record);

					// Call a sort dynamically
					f.firstGridStore.sort('id', 'DESC');

					//Remove Record from the source
					ddSource.grid.store.remove(record);
					f.calcularTotalPeso(record.data.peso);
				}
			}
			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});


	//para mandar del primero al segundo
	var secondGridDropTargetEl = f.secondGrid.getView().el.dom.childNodes[0].childNodes[1];

	var destGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
		ddGroup    : 'secondGridDDGroup',
		copy       : false,
		notifyDrop : function(ddSource, e, data){

			// Generic function to add records.
			function addRow(record, index, allItems) {

				// Search for duplicates
				var foundItem = f.secondGridStore.findExact('id', record.data.id);
				// if not found
				if (foundItem  == -1) {
					f.secondGridStore.add(record);
					f.calcularTotalPeso(record.data.peso,'sumar');
					// Call a sort dynamically
					f.secondGridStore.sort('id', 'DESC');

					//Remove Record from the source
					ddSource.grid.store.remove(record);
				}
			}
			// Loop through the selections
			Ext.each(ddSource.dragData.selections ,addRow);
			return(true);
		}
	});
	
	new Ext.Button({
		hideLabel:true,
		iconCls:'arrowback',
		renderTo:'btnDerE',
		tooltip:'Presione para desagregar todos los envios del embarque',
		handler: function (){
			f.todosParaLaDerecha();
		}
	});
	
	new Ext.Button({
		hideLabel:true,
		iconCls:'arrowforward',
		renderTo:'btnIzqE',
		tooltip:'Presione para agregar todos los envios al embarque',
		handler: function (){
			f.todosParaLaIzquierda();
		}
	});


},500);
 	},
	
	//agregar todos los envios a la derecha "a la lista de Listos pa embarque"
	todosParaLaDerecha: function (){
		var f=this;
		this.secondGridStore.each(function(record){
			f.firstGridStore.add(record);
			f.calcularTotalPeso(record.data.peso);
			f.firstGridStore.sort('id', 'DESC');
			f.secondGridStore.remove(record);
		});		
	},
	
	//agregar a la canasta que se va a embarcar
	todosParaLaIzquierda: function (){
		var f=this;
		this.firstGridStore.each(function(record){
			f.secondGridStore.add(record);
			f.calcularTotalPeso(record.data.peso,'sumar');
			f.secondGridStore.sort('id', 'DESC');
			f.firstGridStore.remove(record);
		});		
	},
	
	calcularTotalPeso: function (peso,operador){
		if(operador=="sumar")
			this.peso_total+=parseFloat(peso);
		else
			this.peso_total-=parseFloat(peso);
		this.labelpeso.setText(this.peso_total.toFixed(2)+"Kg/"+joshua.util.ktol(this.peso_total).toFixed(2)+"Lb");
	}
});

